package com.itheima.tliasbackend.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.itheima.tliasbackend.utils.JwtUtils;
import com.itheima.tliasbackend.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * DemoInterceptor
 *
 * @author liliudong
 * @version 1.0
 * @description
 * @date 2023/5/26 9:30
 */
@Slf4j
@Component
public class LoginCheckInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 不是登录
        // 4. 获取请求头的jwt
        String jwt = request.getHeader("token1");

        // 5.判断jwt是否存在
        if (!StringUtils.hasLength(jwt)) {
            // 不存在Jwt，返回 { "code": 0, "msg": "NOT_LOGIN", "data": null }
            Result notLogin = Result.error("NOT_LOGIN");
            // 对象 --> 序列化 json
            String json = JSONObject.toJSONString(notLogin);
            // 给前端返回json
            response.getWriter().write(json);
            return false;
        }

        // 6. 解析jwt是否合法
        try {
            JwtUtils.parseJWT(jwt);
        } catch (Exception e) {
            Result notLogin = Result.error("NOT_LOGIN");
            // 对象 --> 序列化 json
            String json = JSONObject.toJSONString(notLogin);
            // 给前端返回json
            response.getWriter().write(json);
            return false;
        }

        // 合法放行 - 过滤器链
        return true;
    }
}
